package com.kpx.app.utils;

import java.util.HashMap;
import java.util.Iterator;

/**
 * 陈聪
 * 重写hashmap 用于转换成需要的格式
 */
public class MyHashMap extends HashMap<String, String> {
    /** 变量描述 */
    private static final long serialVersionUID = 1L;

    /**
     * 重写tostring方法，用于将map参数转换成可以加在get请求后面的数据。
     * @return
     */
    @Override
    public String toString() {
        if (isEmpty()) {
            return "{}";
        }

        StringBuilder buffer = new StringBuilder(size() * 28);
        Iterator<Entry<String, String>> it = entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> entry = it.next();
            Object key = entry.getKey();
            if (key != this) {
                buffer.append(key);
            } else {
                buffer.append("(this Map)");
            }
            buffer.append('=');
            Object value = entry.getValue();
            if (value != this) {
                buffer.append(value);
            } else {
                buffer.append("(this Map)");
            }
            if (it.hasNext()) {
                buffer.append("&");
            }
        }
        return buffer.toString();
    }

    /**
     * 将hashmap中的数据转换成json格式
     *
     * @return
     */
    public String toJSONString() {
        if (isEmpty()) {
            return "{}";
        }

        StringBuilder buffer = new StringBuilder(size() * 28);
        Iterator<Entry<String, String>> it = entrySet().iterator();
        buffer.append("{");
        while (it.hasNext()) {
            Entry<String, String> entry = it.next();
            Object key = entry.getKey();
            if (key != this) {
                buffer.append("\"" + key + "\"");
            } else {
                buffer.append("(this Map)");
            }
            buffer.append(':');
            Object value = entry.getValue();
            if (value != this) {
                buffer.append("\"" + value + "\"");
            } else {
                buffer.append("(this Map)");
            }
            if (it.hasNext()) {
                buffer.append(",");
            }
        }
        buffer.append("}");
        return buffer.toString();
    }

}
